package com.atguigu.yygh.hosp.service.impl;

import com.atguigu.yygh.Exception.YyghException;
import com.atguigu.yygh.hosp.repository.DepartmentRepository;
import com.atguigu.yygh.hosp.service.DepartmentService;
import com.atguigu.yygh.model.hosp.Department;
import com.atguigu.yygh.vo.hosp.DepartmentQueryVo;
import com.atguigu.yygh.vo.hosp.DepartmentVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import java.util.stream.Collectors;

@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    DepartmentRepository departmentRepository;

    //上传科室
    @Override
    public void save(Department department) {
        if (department==null){//如果为空直接抛出异常
            throw new YyghException(20001,"参数错误");
        }

        //先从数据库查询是否有该条数据
        Department byDepcodeAndHoscode = departmentRepository.findByDepcodeAndHoscode(department.getDepcode(), department.getHoscode());

        if (byDepcodeAndHoscode!=null){//说明有数据,进行修改
            department.setUpdateTime(new Date());//设置更新时间
            department.setIsDeleted(0);//设置是否逻辑删除
            //设置查询出来数据id值   有id值才会进行修改,否则会添加导致重复添加报错
            department.setId(byDepcodeAndHoscode.getId());
            departmentRepository.save(department);
        }else {//没有数据,进行添加
            department.setUpdateTime(new Date());//设置更新时间
            department.setCreateTime(new Date());//设置创建时间时间
            department.setIsDeleted(0);//设置是否逻辑删除
            departmentRepository.save(department);
        }

    }

    //分页查询科室 带查询条件
    @Override
    public Page<Department> selectPage(Integer page, Integer limit, DepartmentQueryVo departmentQueryVo) {
        //按照创建时间进行降序
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");

        //当前页 从0开始计算,所以 -1
        //每页记录数
        Pageable pageable = PageRequest.of(page-1,limit,sort);

        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写
        //创建department对象
        Department department = new Department();
        //将departmentQueryVo中的属性值复制到department中
        BeanUtils.copyProperties(departmentQueryVo,department);
        department.setIsDeleted(0);//设置 删除状态,:0为删除,1为删除
        //条件封装
        Example<Department> example = Example.of(department, matcher);

        //进行查询,并传入分页条件
        Page<Department> all = departmentRepository.findAll(example, pageable);
        return all;
    }

    //删除科室信息
    @Override
    public void removeByHoscodeAndDepcode(String hoscode, String depcode) {
        //先根据医院编号和科室编号进行查询
      Department department =  departmentRepository.findByDepcodeAndHoscode(hoscode,depcode);
        if(department!=null){//说明有数据
            //有数据进行删除 根据id进行删除
            departmentRepository.deleteById(department.getId());
        }
        //如果没有数据,则不惊醒操作
    }

    //根据hoscode查询所有的Department(科室)
    @Override
    public List<DepartmentVo> getDeptList(String hoscode) {
        ArrayList<DepartmentVo> departmentVos = new ArrayList<>();

        //获取所有的科室列表
        List<Department>  allDepartmentList= departmentRepository.findByHoscode(hoscode);

        //根据大科室编号  bigcode 分组，获取每个大科室里面下级子科室
        //使用流的方式对list集合进行分组, 按照bigCode 分组
        //map集合中的key值为bigCode的值 value值是大科室对应的小科室
        Map<String, List<Department>> departmentMap = allDepartmentList.stream().collect(Collectors.groupingBy(Department::getBigcode));
        //遍历map集合
        for(Map.Entry<String, List<Department>> entry:departmentMap.entrySet()){
            String bigCode = entry.getKey();//获取大科室的code值
            List<Department> smallDept = entry.getValue();//获取大科室对应的所有小科室

            //封装大科室
            DepartmentVo bigDept = new DepartmentVo();
            bigDept.setDepcode(bigCode);//小科室的bigCode是大科室的depCode(科室编号)
            bigDept.setDepname(smallDept.get(0).getBigname());//小科室的bigName 为大科室的depName

            //封装大科室里的小科室
            //创建一个小科室集合
            List<DepartmentVo> children = new ArrayList<>();
            //遍历大科室对应的所有小科室
            for (Department department : smallDept) {
                //创建
                DepartmentVo departmentVo = new DepartmentVo();
                departmentVo.setDepname(department.getDepname());
                departmentVo.setDepcode(department.getDepcode());
                //封装到小科室集合中
                children.add(departmentVo);
            }
            //将小科室封装进大科室里的children中
            bigDept.setChildren(children);
            //将大科室(包含封装好的小科室)放到list里并返回
            departmentVos.add(bigDept);
        }

        return departmentVos;
    }

    //根据医院编码 和 科室编码获取 获取科室名称
    @Override
    public String getDepName(String hoscode, String depcode) {
        Department byDepcodeAndHoscode = departmentRepository.findByDepcodeAndHoscode(depcode, hoscode);
        String depname = byDepcodeAndHoscode.getDepname();
        return depname;
    }
}
